package script.quizview
{
	import laya.events.Event;
	import laya.media.SoundManager;
	
	import model.quiz.MathQuestionVo;
	import model.quiz.MathQuizModel;
	
	import script.ViewManager;
	import script.baseView.BaseViewController;
	import script.commontool.NumerInputTool;
	
	import ui.quiz.MathQuizPanelUI;
	
	
	public class MathQuizeController extends BaseViewController
	{
		private var uiSkin:MathQuizPanelUI;
		
		private var curIndex:int = 0;
		public function MathQuizeController()
		{
			super();
		}
		
		override public function onStart():void
		{
			uiSkin = this.owner as MathQuizPanelUI;
			updateQuestion();
			
			NumerInputTool.instance.showGui(uiSkin,uiSkin.answertxt);
			
			uiSkin.oktbn.on(Event.CLICK,this,onConfirmAnser);
			uiSkin.jumpnext.on(Event.CLICK,this,onJumpQuestion);
			
			uiSkin.jumpnext.visible = false;

		}
		
		private function updateQuestion():void
		{
			if(MathQuizModel.instance.questionList.length > curIndex)
			{
				var question:MathQuestionVo = MathQuizModel.instance.questionList[curIndex];
				
				var questitle:String = question.numlist[0] + "";
				for(var i:int=0;i < question.operateList.length;i++)
				{
					questitle += ["+","-"][question.operateList[i] - 1] + question.numlist[i+1];
				}
				
				uiSkin.questiontxt.text = questitle;
				
				uiSkin.answertxt.text = "";
				
				uiSkin.numpage.text = (curIndex + 1) + "/" + MathQuizModel.instance.questionList.length;
				
				uiSkin.jumpnext.visible = false;

			}
		}
		
		private function onConfirmAnser():void
		{
			MathQuizModel.instance.questionList[curIndex].myanswer = parseInt(uiSkin.answertxt.text);
			
			if(parseInt(uiSkin.answertxt.text) == MathQuizModel.instance.questionList[curIndex].answer)
			{
				SoundManager.playSound("sound/common/answerright.mp3");
				
				if(curIndex < MathQuizModel.instance.questionList.length - 1)
				{
					curIndex++;
					updateQuestion();
				}
				else
				{
					MathQuizModel.instance.calculateScore();
					ViewManager.instance.closeView(ViewManager.VIEW_MATHQUIZ_PANEL);

					ViewManager.instance.openView(ViewManager.VIEW_MATHQUIZ_RESULT_PANEL);
				}

			}
			else
			{
				SoundManager.playSound("sound/common/anwserrong.mp3");
				uiSkin.jumpnext.visible = true;


			}
		}
		
		private function onJumpQuestion():void
		{
			if(curIndex < MathQuizModel.instance.questionList.length - 1)
			{
				curIndex++;
				updateQuestion();
			}
			else
			{
				MathQuizModel.instance.calculateScore();
				ViewManager.instance.closeView(ViewManager.VIEW_MATHQUIZ_PANEL);
				ViewManager.instance.openView(ViewManager.VIEW_MATHQUIZ_RESULT_PANEL);
			}
		}
		
		override public function onDestroy():void
		{
			NumerInputTool.instance.hide();
		}
	}
}